package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryHotBlog(Integer current) {

        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::queryBlogUser);
        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 查找前5个点赞博客的用户，从redis里面
        String key = "blog:liked:" + id;
        Long count = stringRedisTemplate.opsForZSet().zCard(key);
        if (count == null || count == 0) {
            // ok里面返回空，表示没有点赞记录
            return Result.ok(Collections.emptyList());
        }
        /**
         * @description TODO
         * @author: sats@jz
         * @param  : id - [java.lang.Long]
         * @return : com.hmdp.dto.Result
         * stream() 方法是用于创建一个新的流的操作。对于 Collector 来说，它通常用于将收集器（如 Collectors.toList()、Collectors.toSet() 等）应用于流中的元素，以实现元素的收集和汇聚。
         * stream().map() 它接受一个函数作为参数，该函数定义了如何转换流中的每个元素。map 返回一个新的流，包含转换后的元素。
         **/
        List<Long> ids = stringRedisTemplate.opsForZSet().range(key, 0, 4).stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id,"+ StrUtil.join(",", ids) +")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result likeBlog(Long id) {
        UserDTO userDTO = UserHolder.getUser();
        // 从redis 中查询是否点赞，数据结构ZSET, key为博文ID，Value为用户id，score为点赞时间戳
        String key = "blog:liked:" + id;
        Double time = stringRedisTemplate.opsForZSet().score(key, userDTO.getId().toString());
        if (time == null) {
            // 如果没有点赞，就点赞
            // 更新blog的点赞数量
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 保存用户到redis的set集合中
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userDTO.getId().toString(), System.currentTimeMillis());
            }
        }else{
            // 如果已经点赞，就取消点赞
            // 更新blog的点赞数量
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 从redis的set集合中移除用户
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userDTO.getId().toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            throw new RuntimeException("博文不存在");
        }
        //查询用户
        queryBlogUser(blog);
        return Result.ok(blog);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = UserHolder.getUser().getId();
        // 查询自己是否点赞了这个博客
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
        User user = userService.getById(userId);
        if (user == null){
            throw new RuntimeException("用户不存在");
        }
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
    }


}
